<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html>
<head>
    <title>添加销售记录</title>
    <style>
        /* 整体页面样式 */
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f5;
            margin: 0;
            padding: 0;
            color: #333;
        }

        /* 主容器样式 */
        .main-container {
            width: 60%;
            margin: 30px auto;
            padding: 20px;
            background-color: white;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }

        /* 标题样式 */
        h1 {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
            margin-bottom: 15px;
        }

        /* 表单通用样式 */
        form {
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f9f9f9;
        }

        /* 标签样式 */
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }

        /* 输入框样式 */
        input[type="text"],
        input[type="number"],
        input[type="date"],
        select {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 3px;
            box-sizing: border-box;
            transition: border-color 0.3s ease;
        }

        input[type="text"]:focus,
        input[type="number"]:focus,
        input[type="date"]:focus,
        select:focus {
            border-color: #007bff;
        }

        /* 下拉菜单样式 */
        select {
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23333"><path d="M7 10l5 5 5-5z"/></svg>') no-repeat right 10px center;
            background-size: 12px 12px;
        }

        /* 按钮样式 */
        input[type="submit"],
        .back-button {
            display: inline-block;
            text-decoration: none;
            padding: 10px 20px;
            border-radius: 3px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease, box-shadow 0.3s ease;
            margin-bottom: 10px;
        }

        input[type="submit"] {
            color: white;
            background-color: #28a745;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
        }

        input[type="submit"]:hover {
            opacity: 0.8;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }

        .back-button {
            color: white;
            background-color: #6c757d;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .back-button:hover {
            opacity: 0.8;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
        }

        /* 错误信息样式 */
        .error-message {
            color: #dc3545;
            margin-bottom: 10px;
            font-size: 14px;
            display: none;
        }

        .id-exists-message {
            color: #dc3545;
            margin-bottom: 10px;
            font-size: 14px;
            display: none;
        }

        /* 表单元素分组样式，增加元素之间的间距 */
        .form-group {
            margin-bottom: 30px;
        }

        /* 按钮容器样式，将按钮水平排列并添加间距 */
        .button-container {
            display: flex;
            justify-content: flex-end;
            gap: 20px;
            margin-top: 20px;
        }

        /* 只读输入框样式 */
        input[readonly] {
            background-color: #e9ecef;
            border-color: #ced4da;
            cursor: not-allowed;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function () {
            // 同步商品或人员相关字段
            function updateFieldName(fieldType, id) {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', 'get' + fieldType + 'NameById?id=' + id, true);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var response = JSON.parse(xhr.responseText);
                        $('#' + fieldType + '_name').val(response.name);
                    }
                };
                xhr.send();
            }

            // 检查销售记录 ID 是否存在
            function checkSaleBillIDExists() {
                var saleBillID = $('#saleBillID').val();
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var exists = JSON.parse(xhr.responseText);
                        $('#saleBillIDExistsError').toggle(exists);
                    }
                };
                xhr.open('GET', 'checkSaleBillIDExists.action?id=' + saleBillID, true);
                xhr.send();
            }

            // 表单提交验证
            $('#addForm').submit(function (e) {
                var isValid = true;
                var errorMessages = [];
                var saleBillID = $('#saleBillID').val();
                var goodsId = $('#goods_id').val();
                var goodsName = $('#goods_name').val();
                var saleDate = $('#sale_Date').val();
                var number = $('#number').val();
                var personId = $('#person_id').val();
                var personName = $('#person_name').val();
                var saleBillIDError = $('#saleBillIDError');
                var goodsIdError = $('#goodsIdError');
                var saleDateError = $('#saleDateError');
                var numberError = $('#numberError');
                var personIdError = $('#personIdError');

                // 销售记录 ID 验证
                if (saleBillID === '') {
                    saleBillIDError.text('销售记录 ID 不能为空');
                    saleBillIDError.show();
                    errorMessages.push('销售记录 ID 不能为空');
                    isValid = false;
                } else if (!/^[a-zA-Z0-9]{1,20}$/.test(saleBillID)) {
                    saleBillIDError.text('销售记录 ID 必须由字母、数字组成，长度不超过 20 个字符');
                    saleBillIDError.show();
                    errorMessages.push('销售记录 ID 必须由字母、数字组成，长度不超过 20 个字符');
                    isValid = false;
                } else {
                    saleBillIDError.hide();
                }

                // 商品 ID 和名称匹配验证
                if (!goodsId || !goodsName) {
                    goodsIdError.text('请确保商品 ID 和商品名称相互匹配');
                    goodsIdError.show();
                    errorMessages.push('请确保商品 ID 和商品名称相互匹配');
                    isValid = false;
                } else {
                    goodsIdError.hide();
                }

                // 销售时间验证
                if (saleDate === '') {
                    saleDateError.text('销售时间不能为空');
                    saleDateError.show();
                    errorMessages.push('销售时间不能为空');
                    isValid = false;
                } else {
                    saleDateError.hide();
                }

                // 销售数量验证
                if (number === '') {
                    numberError.text('销售数量不能为空');
                    numberError.show();
                    errorMessages.push('销售数量不能为空');
                    isValid = false;
                } else if (!/^\d+$/.test(number) || parseInt(number) <= 0) {
                    numberError.text('销售数量必须为正整数');
                    numberError.show();
                    errorMessages.push('销售数量必须为正整数');
                    isValid = false;
                } else {
                    numberError.hide();
                }

                // 销售人员 ID 和姓名匹配验证
                if (!personId || !personName) {
                    personIdError.text('请确保销售人员 ID 和销售人员姓名相互匹配');
                    personIdError.show();
                    errorMessages.push('请确保销售人员 ID 和销售人员姓名相互匹配');
                    isValid = false;
                } else {
                    personIdError.hide();
                }

                if (!isValid) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: '错误',
                        text: errorMessages.join('\n'),
                    });

                } else {
                    var formData = $(this).serialize();
                    $.ajax({
                        url: 'saleBill.action?action=save',
                        type: 'POST',
                        data: formData,
                        success: function (result) {
                            if (result.startsWith("添加成功")) {
                                Swal.fire({
                                    icon: 'success',
                                    title: '成功',
                                    text: '销售信息添加成功',
                                }).then(function () {
                                    // 刷新到指定页面，例如 index.html
                                    window.location.href = 'saleBill.action?action=list';
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: '失败',
                                    text: result
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: '请求出错',
                                text: '出现网络问题或服务器错误，请稍后再试'
                            });
                        }
                    });
                }
            });

            // 绑定商品 ID 选择事件
            $('#goods_id').change(function () {
                updateFieldName('goods', $(this).val());
            });

            // 绑定销售人员 ID 选择事件
            $('#person_id').change(function () {
                updateFieldName('person', $(this).val());
            });

            // 绑定销售记录 ID 输入事件
            $('#saleBillID').on('input', checkSaleBillIDExists);
        });
    </script>
</head>
<body>
<div class="main-container">
    <h1>添加销售记录</h1>
    <form action="saleBill.action?action=save" method="post" id="addForm" onsubmit="return false">
        <div class="form-group">
            <label for="saleBillID">销售记录 ID</label>
            <input type="text" id="saleBillID" name="saleBillID" required>
            <span class="error-message" id="saleBillIDError"></span>
            <span class="id-exists-message" id="saleBillIDExistsError">该销售记录 ID 已存在，请重新输入</span>
        </div>
        <div class="form-group">
            <label for="goods_id">商品 ID</label>
            <select id="goods_id" name="goods_id">
                <c:forEach items="${goodsList}" var="goods">
                    <option value="${goods.id}">${goods.id}</option>
                </c:forEach>
            </select>
        </div>
        <div class="form-group">
            <label for="goods_name">商品名称</label>
            <input type="text" id="goods_name" name="goods_name" readonly>
            <span class="error-message" id="goodsIdError"></span>
        </div>
        <div class="form-group">
            <label for="sale_Date">销售时间</label>
            <input type="date" id="sale_Date" name="sale_Date" required>
            <span class="error-message" id="saleDateError"></span>
        </div>
        <div class="form-group">
            <label for="number">销售数量</label>
            <input type="number" id="number" name="number" required>
            <span class="error-message" id="numberError"></span>
        </div>
        <div class="form-group">
            <label for="person_id">销售人员 ID</label>
            <select id="person_id" name="person_id">
                <c:forEach items="${personList}" var="person">
                    <option value="${person.id}">${person.id}</option>
                </c:forEach>
            </select>
        </div>
        <div class="form-group">
            <label for="person_name">销售人员姓名</label>
            <input type="text" id="person_name" name="person_name" readonly>
            <span class="error-message" id="personIdError"></span>
        </div>
        <div class="button-container">
            <input type="submit" value="提交">
            <a href="saleBill.action?action=list" class="back-button">返回</a>
        </div>
    </form>
</div>
</body>
</html>